package cn.murky.admin.system.biz.mq;

import cn.murky.admin.system.api.domian.bo.SysI18nBO;
import cn.murky.admin.tenant.api.TenantEnvApi;
import cn.murky.common.domain.bo.SysDictBO;
import cn.murky.redismq.RedisMqTemplate;
import lombok.extern.slf4j.Slf4j;
import org.noear.redisx.RedisClient;
import org.noear.snack.ONode;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;

import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class I18nRedisMqTemplate implements RedisMqTemplate {
    @Inject
    private RedisClient redisClient;
    @Inject
    private TenantEnvApi tenantEnvApi;
    public void publish(List<SysI18nBO> sysI18nBOS) {
        log.info("[I18nRedisMqTemplate] -> publish 发布消息 topic:{}", getTopic());
        redisClient.getBus().publish(getTopic(), ONode.serialize(sysI18nBOS));
    }

    @Override
    public void subscribe() {
        log.info("[I18nRedisMqTemplate] -> 订阅主题 -> topic:{}", getTopic());
        redisClient.getBus().subscribe((topic, msg) -> {
            // 分布式锁,在集群环境下防止重复刷新缓存
            if (redisClient.getLock(getTopic() + ":LOCK").tryLock(5)) {
                log.info("[I18nRedisMqTemplate] -> 消费消息 -> topic:{},msg:{}", topic, msg);
                List<SysI18nBO> sysI18nBOList = ONode.deserialize(msg, (new ArrayList<SysI18nBO>() {
                }).getClass());
                tenantEnvApi.refreshI18n(sysI18nBOList);
            }
        }, getTopic());
    }

    @Override
    public String getTopic() {
        return "topic:i18n:data";
    }
}
